﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Silverlight.DataGrid;
using System.Reflection;
using System.Collections.ObjectModel;
using ExameRegister.Model;


namespace ExameRegister
{
    public class DictTextBox : ContentControl
    {
        public static DependencyProperty FieldProperty;

        public string Field
        {
            get
            {
                return (string)base.GetValue(FieldProperty);
            }
            set
            {
                base.SetValue(FieldProperty, value);
                if(ResultValue != null)
                    InitailControl(ResultValue);
            }
        }


        private bool _WriteValueWithParent;

        public bool WriteValueWithParent
        {
            get { return _WriteValueWithParent; }
            set { _WriteValueWithParent = value; }
        }
        

        private bool _AddEmptyValue;

        public bool AddEmptyValue
        {
            get { return _AddEmptyValue; }
            set { _AddEmptyValue = value; }
        }

        private Control _ParentControl;

        public Control ParentControl
        {
            get { return _ParentControl; }
            set
            {
                _ParentControl = value;
                if (value != null)
                {
                    _ParentControl.MouseLeftButtonDown += new MouseButtonEventHandler(_ParentControl_MouseLeftButtonDown);
                }
            }
        }

        void _ParentControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (btton != null)
            {
                btton_Click(btton, null);
            }
        }
        
        

        //protected override void OnContentChanged(object oldContent, object newContent)
        //{
        //    base.OnContentChanged(oldContent, newContent);
        //    if (null == newContent || string.IsNullOrEmpty(Field))
        //        return;
        //    PropertyInfo pi = newContent.GetType().GetProperty(Field);
        //    object obj = pi.GetValue(newContent, null);
        //    C1DataGrid cg = (C1DataGrid)this.GetTemplateChild("DataGrid1");
        //    ObservableCollection<DataDictionaryItemModel> Items = cg.ItemsSource as ObservableCollection<DataDictionaryItemModel>;
        //    DataDictionaryItemModel item = null;
        //    switch (DictResultType)
        //    {
        //        case DictResultType.ID:
        //            item = Items.Where(c => c.Id == (int)obj).FirstOrDefault();
        //            break;

        //        case DictResultType.Code:
        //            item = Items.Where(c => c.DictCode == obj.ToString()).FirstOrDefault();
        //            break;
        //        case DictResultType.Name:
        //            item = Items.Where(c => c.DictValue == obj.ToString()).FirstOrDefault();
        //            break;
        //    }
        //    cg.SelectedItem = item;

        //}

        static DictTextBox()
        {

            FieldProperty = DependencyProperty.Register("Field",
                                           typeof(string),
                                           typeof(DictTextBox),
                                           new PropertyMetadata("默认属性值", new PropertyChangedCallback(DictTextBox.OnFieldPropertyChanged)));
        }

        private string[] _Parameter;
        /// <summary>
        /// 参数的书写格式为: param=value
        /// Sql中的参数书写格式为: column=:param
        /// </summary>
        public string[] Parameter
        {
            get { return _Parameter; }
            set
            {
                _Parameter = value;
                foreach (string s in _Parameter)
                {
                    _ParamString += s + ";";
                }
                this.OnApplyTemplate();
            }
        }

        private string _ParamString = string.Empty;

        private ServiceUtility client = null;

        private static void OnFieldPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as DictTextBox).OnFieldPropertyChanged(e);
        }

        void OnFieldPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            try
            {
                //TextBlock BgTextBlock = this.GetTemplateChild("ButtonCaption") as TextBlock;
                //BgTextBlock.Text = e.NewValue as string;
            }
            catch (Exception ex)
            {
                string ks = ex.ToString();
            }

        }

        private string _DictCode;

        public string DictCode
        {
            get { return _DictCode; }
            set { _DictCode = value; }
        }

        private string _DictSql;

        public string DictSql
        {
            get { return _DictSql; }
            set { _DictSql = value; }
        }

        private bool _IsNoNLeafSelectable = false;

        public bool IsNoNLeafSelectable
        {
            get { return _IsNoNLeafSelectable; }
            set { _IsNoNLeafSelectable = value; }
        }


        private DictViewType _DictViewType;

        public DictViewType DictViewType
        {
            get { return _DictViewType; }
            set { _DictViewType = value; }
        }

        private DictResultType _DictResultType;

        public DictResultType DictResultType
        {
            get { return _DictResultType; }
            set { _DictResultType = value; }
        }


        public DictTextBox()
        {
            this.DefaultStyleKey = typeof(DictTextBox);
            client = new ServiceUtility();
        }





        #region 控件集合
        private Image imgRefresh = null;//刷新按钮
        private TreeView tw = null;
        private DataDictionaryModel ResultValue = null;
        private BusyIndicator indicator = null;
        private TextBox tbSearch = null;
        Button btton = null;
        private System.Windows.Controls.Primitives.Popup pop = null;
        #endregion

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            btton = (Button)this.GetTemplateChild("Button1");
            // Grid gd=(Grid)this.GetTemplateChild("root");
            if (btton != null)
            {
                FrameworkElement fe = this;
                while (GetParentUI(fe) != null)
                {
                    fe = fe.Parent as FrameworkElement;
                    fe.MouseLeftButtonDown += new MouseButtonEventHandler(fe_MouseLeftButtonDown);
                }
                //System.Windows.Interop.Content contentObject = this;
                //contentObject.IsFullScreen = !contentObject.IsFullScreen;
                
                btton.Click -= new RoutedEventHandler(btton_Click);
                btton.Click += new RoutedEventHandler(btton_Click);
                //this.GotFocus -= new RoutedEventHandler(DictTextBox_GotFocus);
                //this.GotFocus += new RoutedEventHandler(DictTextBox_GotFocus);
                //this.LostFocus -= new RoutedEventHandler(DictTextBox_LostFocus);
                //this.LostFocus += new RoutedEventHandler(DictTextBox_LostFocus);
                C1DataGrid dg = (C1DataGrid)this.GetTemplateChild("DataGrid1");
                pop = (System.Windows.Controls.Primitives.Popup)this.GetTemplateChild("Popup1");
                //pop.MouseLeave += (sender, e) =>
                //{
                //    pop.IsOpen = false;
                //};
               
                if (dg != null)
                {
                    dg.SelectionChanged -= new EventHandler<DataGridSelectionChangedEventArgs>(dg_SelectionChanged);
                    dg.SelectionChanged += new EventHandler<DataGridSelectionChangedEventArgs>(dg_SelectionChanged);
                }
                imgRefresh = (Image)this.GetTemplateChild("btRefresh");
                imgRefresh.MouseLeftButtonDown -= new MouseButtonEventHandler(imgRefresh_MouseLeftButtonDown);
                imgRefresh.MouseLeftButtonDown += new MouseButtonEventHandler(imgRefresh_MouseLeftButtonDown); //+= new RoutedEventHandler(btnRefresh_Click);
                tbSearch = (TextBox)this.GetTemplateChild("TextBox2");
                //tbSearch.GotFocus -= new RoutedEventHandler(tbSearch_GotFocus);
                //tbSearch.GotFocus += new RoutedEventHandler(tbSearch_GotFocus);
                tbSearch.TextChanged -= new TextChangedEventHandler(tbSearch_TextChanged);
                tbSearch.TextChanged += new TextChangedEventHandler(tbSearch_TextChanged);
                //this.tbSearch.LostFocus -= new RoutedEventHandler(this.tbSearch_LostFocus);
                //this.tbSearch.LostFocus += new RoutedEventHandler(this.tbSearch_LostFocus);

                indicator = (BusyIndicator)this.GetTemplateChild("xBusy");
                Canvas can = (Canvas)this.GetTemplateChild("Can");
                can.MouseLeftButtonDown += new MouseButtonEventHandler(can_MouseLeftButtonDown);
                indicator.IsBusy = true;
                indicator.BusyContent = "Loading...";
                client.OnCompletedCallService -= new EventHandler<WCFEvent>(client_OnCompletedCallService);
                client.OnCompletedCallService += new EventHandler<WCFEvent>(client_OnCompletedCallService);
                client.CallService("ExameRegister.BO.LoginBO", "GetDataDictionaryModel", new object[] { DictCode, _ParamString }, this);
                //client.GetDictModelAsync(DictCode, _ParamString); 
                //client.GetDictModelCompleted -= new EventHandler<GetDictModelCompletedEventArgs>(client_GetDictModelCompleted);
                //client.GetDictModelCompleted += new EventHandler<GetDictModelCompletedEventArgs>(client_GetDictModelCompleted);
                //pop.GotFocus -= new RoutedEventHandler(pop_GotFocus);
                //pop.GotFocus += new RoutedEventHandler(pop_GotFocus);
                // pop.LostFocus -= new RoutedEventHandler(DictTextBox_LostFocus);

                Grid gd1 = (Grid)this.GetTemplateChild("root");
                gd1.MouseLeftButtonDown += new MouseButtonEventHandler(gd1_MouseLeftButtonDown);

            }

        }

        void fe_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            pop.IsOpen = false;
        }

        FrameworkElement GetParentUI(FrameworkElement ui)
        {
            return ui.Parent as FrameworkElement;
        }

        void client_OnCompletedCallService(object sender, WCFEvent e)
        {
            DataDictionaryModel result = Utility.ConvertFromJson<DataDictionaryModel>(e.Result);
            indicator.IsBusy = false;
            ResultValue = result;
            if (AddEmptyValue == true)
                ResultValue.Item.Add(new DataDictionaryItemModel() { Id = -1, DictCode = "Null", DictValue = "Null", DictPinYin = "Null", ParentId = 0 });
            if (result == null || result.Item.Count <= 0)
                return;
            InitailControl(ResultValue);
        }

        void gd1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //throw new NotImplementedException();
            pop.IsOpen = !pop.IsOpen;
        }

        void can_LostFocus(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void can_GotFocus(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            pop.IsOpen = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void can_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //throw new NotImplementedException();
            pop.IsOpen = !pop.IsOpen;

        }

        //private void ResizeOvelay(Canvas overLay)
        //{
        //    //获取Silverlight的整个可见区域大小
        //    double pageWidth = Application.Current.Host.Content.ActualWidth;
        //    double pageHeight = Application.Current.Host.Content.ActualHeight;
        //    //获取Popup在整个可见区域的位置
        //    Point popContentPosition = popContent.TransformToVisual(null).Transform(new Point(0, 0));
        //    //将Overlay调整至与可见区域相同大小
        //    overLay.Width = pageWidth;
        //    overLay.Height = pageHeight;
        //    //移动Canvas到可见区域左上角以填充整个区域
        //    overLay.RenderTransform = new TranslateTransform() { X = -popContentPosition.X, Y = -popContentPosition.Y };
        //    //Popup的内容会跟着Canvas移动到左上角，因此平移到原来的位置
        //}

        void DictTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void pop_LostFocus(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            pop.IsOpen = false;
        }

        void pop_GotFocus(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            var aa = (Grid)sender;

        }

        void tbSearch_GotFocus(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void gd_LostFocus(object sender, RoutedEventArgs e)
        {
            //sthrow new NotImplementedException();
            pop.IsOpen = false;
        }
        //private void _TextBox_LostFocus(object sender, RoutedEventArgs e)

        void tbSearch_LostFocus(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            pop.IsOpen = false;
        }

        void DictTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            pop.IsOpen = false;
        }

        /// <summary>
        /// 刷新按钮动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void imgRefresh_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            indicator.IsBusy = true;
            //client.GetDictModelAsync(DictCode, _ParamString);
            client.CallService("ExameRegister.BO.LoginBO", "GetDataDictionaryModel", new object[] { DictCode, _ParamString }, this);
        }

        /// <summary>
        /// 搜索框

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tbSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            string text = tbSearch.Text;
            DataDictionaryModel data = new DataDictionaryModel() { IsTree = ResultValue.IsTree };
            if (!string.IsNullOrEmpty(text))
            {
                data.Item = new ObservableCollection<DataDictionaryItemModel>
                    (ResultValue.Item.Where(c => c.DictCode.Contains(text) || c.DictPinYin.Contains(text) || c.DictValue.Contains(text)));
                InitailControl(data);
            }
            else
            {
                data.Item = ResultValue.Item;
                InitailControl(data);
                //indicator.IsBusy = true;
                //client.GetDictModelAsync(this.DictCode, _ParamString);
            }
        }



        //void client_GetDictModelCompleted(object sender, GetDictModelCompletedEventArgs e)
        //{
        //    indicator.IsBusy = false;
        //    ResultValue = e.Result;
        //    if (AddEmptyValue == true)
        //        ResultValue.Item.Add(new WCFService.DataDictionaryItemModel() { Id = -1, DictCode = "Null", DictValue = "Null", DictPinYin = "Null", ParentId = 0 });
        //    if (e.Result == null || e.Result.Item.Count <= 0)
        //        return;
        //    InitailControl(ResultValue);
        //}

        void InitailControl(DataDictionaryModel _ResultValue)
        {
            C1DataGrid dg = (C1DataGrid)this.GetTemplateChild("DataGrid1");

            #region 树型数据字典

            if (_ResultValue.IsTree)
            {
                Grid g = (Grid)this.GetTemplateChild("Grid1");
                if (g != null && g.Children.Count >= 2)
                {
                    g.Children.RemoveAt(0);
                }
                tw = new TreeView();
                tw.Margin = new Thickness(0, 0, 0, 29);
                //tw.MouseLeftButtonDown -= new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                //tw.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                g.Children.Insert(0, tw);
                foreach (var i in _ResultValue.Item.Where(c => c.ParentId == 0))
                {
                    TreeViewItem tvi = new TreeViewItem();//{ Header = "[" + i.Id + "]" + i.DictCode };
                    tvi.DataContext = i;
                    AddTreeNode(tvi, i.Id, _ResultValue.Item);
                    if (IsNoNLeafSelectable == false)//非叶子节点不可以选择
                    {
                        if (tvi.Items.Count <= 0)//叶子节点可以点击
                        {
                            AddTreeHead(tvi, i, true);
                            //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                            //link.Click += new RoutedEventHandler(link_Click);
                            //tvi.Header = link;
                            //tvi.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                        }
                        else
                        {
                            //tvi.Header = "[" + i.Id + "]" + i.DictCode;
                            AddTreeHead(tvi, i, false);
                        }
                    }
                    else//所有节点都可以选择
                    {
                        //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                        //link.Click += new RoutedEventHandler(link_Click);
                        //tvi.Header = link;
                        AddTreeHead(tvi, i, true);
                    }
                    tw.Items.Add(tvi);
                }
                if (!string.IsNullOrEmpty(Field) && this.DataContext != null)
                {
                    object obj = this.DataContext;
                    PropertyInfo pi = obj.GetType().GetProperty(Field);
                    if (pi != null)
                    {
                        object value = pi.GetValue(obj, null);
                        if (value == null || string.IsNullOrEmpty(value.ToString()))
                            return;
                        DataDictionaryItemModel SelectItem = null;
                        switch (DictResultType)
                        {
                            case DictResultType.ID:
                                SelectItem = _ResultValue.Item.Where(c => c.Id == (int)value).FirstOrDefault();
                                break;
                            case DictResultType.Code:
                                SelectItem = _ResultValue.Item.Where(c => c.DictCode == value.ToString()).FirstOrDefault();
                                break;
                            case DictResultType.Name:
                                SelectItem = _ResultValue.Item.Where(c => c.DictValue == value.ToString()).FirstOrDefault();
                                break;
                        }
                        if (_WriteValueWithParent == true && this.DictResultType == ExameRegister.DictResultType.Name && this.DictViewType == ExameRegister.DictViewType.Name)
                        {
                            DataDictionaryItemModel newItem = new DataDictionaryItemModel() { DictValue = value.ToString() };
                            SetText(newItem);
                        }else
                            SetText(SelectItem);
                    }
                }

                return;
            }
            #endregion

            #region 普通数据字典
            dg.Columns[0].Header = "编码";
            dg.Columns[1].Header = "名称";
            //dg.Columns[0].
            dg.ItemsSource = _ResultValue.Item;
            //初始化如果有值， 自动绑定上

            if (!string.IsNullOrEmpty(Field) && this.DataContext != null)
            {
                object obj = this.DataContext;
                PropertyInfo pi = obj.GetType().GetProperty(Field);
                if (pi != null)
                {
                    object value = pi.GetValue(obj, null);
                    if (value == null || string.IsNullOrEmpty(value.ToString()))
                        return;
                    DataDictionaryItemModel SelectItem = null;
                    switch (DictResultType)
                    {
                        case DictResultType.ID:
                            SelectItem = _ResultValue.Item.Where(c => c.Id == (int)value).FirstOrDefault();
                            break;
                        case DictResultType.Code:
                            SelectItem = _ResultValue.Item.Where(c => c.DictCode == value.ToString()).FirstOrDefault();
                            break;
                        case DictResultType.Name:
                            SelectItem = _ResultValue.Item.Where(c => c.DictValue == value.ToString()).FirstOrDefault();
                            break;
                    }
                    SetText(SelectItem);
                }
            }
            #endregion
        }

        void link_Click(object sender, RoutedEventArgs e)
        {
            TreeView dg = tw;
            if (dg.SelectedItem != null)
            {
                if (_WriteValueWithParent == true && this.DictResultType== ExameRegister.DictResultType.Name &&　this.DictViewType == ExameRegister.DictViewType.Name)
                {
                    var item = (dg.SelectedItem as TreeViewItem).DataContext as DataDictionaryItemModel;
                    DataDictionaryItemModel newItem = new DataDictionaryItemModel(){DictValue= item.DictValue};
                    while (ResultValue.Item.Where(c => c.Id == item.ParentId && c.ParentId !=0).Count() > 0)
                    {
                        item = ResultValue.Item.Where(c => c.Id == item.ParentId).FirstOrDefault();
                        newItem.DictValue = item.DictValue + newItem.DictValue;
                    }
                    SetText(newItem);
                }else
                    SetText((dg.SelectedItem as TreeViewItem).DataContext as DataDictionaryItemModel);
            }

            pop.IsOpen = false;
        }

        void AddTreeHead(TreeViewItem tvi, DataDictionaryItemModel item, bool Selectedable)
        {
            HyperlinkButton hlb = new HyperlinkButton();
            hlb.Click += new RoutedEventHandler(link_Click);
            switch (this.DictViewType)
            {
                case DictViewType.ID:
                    if (Selectedable)
                    {
                        hlb.Content = item.Id;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = item.Id;
                    break;
                case DictViewType.Code:
                    if (Selectedable)
                    {
                        hlb.Content = item.DictCode;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = item.DictCode;
                    break;
                case DictViewType.Name:
                    if (Selectedable)
                    {
                        hlb.Content = item.DictValue;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = item.DictValue;
                    break;
                case DictViewType.IDAndName:
                    if (Selectedable)
                    {
                        hlb.Content = "[" + item.Id + "]" + item.DictValue;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = "[" + item.Id + "]" + item.DictValue;
                    break;
                case DictViewType.CodeAndName:
                    if (Selectedable)
                    {
                        hlb.Content = "[" + item.DictCode + "]" + item.DictValue;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = "[" + item.DictCode + "]" + item.DictValue;
                    break;
            }
        }

        void AddTreeNode(TreeViewItem pitem, int pid, ObservableCollection<DataDictionaryItemModel> source)
        {
            foreach (var i in source.Where(c => c.ParentId == pid))
            {
                TreeViewItem tvi = new TreeViewItem();//{ Header = "[" + i.Id + "]" + i.DictCode };
                tvi.DataContext = i;
                AddTreeNode(tvi, i.Id, source);
                //if (tvi.Items.Count <= 0)//叶子节点可以点击
                //{
                //    tvi.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                //}

                if (IsNoNLeafSelectable == false)//非叶子节点不可以选择
                {
                    if (tvi.Items.Count <= 0)//叶子节点可以点击
                    {
                        AddTreeHead(tvi, i, true);
                        //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                        //link.Click += new RoutedEventHandler(link_Click);
                        //tvi.Header = link;
                        //tvi.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                    }
                    else
                    {
                        //tvi.Header = "[" + i.Id + "]" + i.DictCode;
                        AddTreeHead(tvi, i, false);
                    }
                }
                else//所有节点都可以选择
                {
                    //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                    //link.Click += new RoutedEventHandler(link_Click);
                    //tvi.Header = link;
                    AddTreeHead(tvi, i, true);
                }
                //if (tvi.Items.Count <= 0)//叶子节点可以点击
                //{
                //    HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                //    link.Click += new RoutedEventHandler(link_Click);
                //    tvi.Header = link;
                //    //tvi.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                //}
                //else
                //{
                //    tvi.Header = "[" + i.Id + "]" + i.DictCode;
                //}
                pitem.Items.Add(tvi);
            }
        }

        /// <summary>
        /// 
        /// </summary>        
        /// <param name="item"></param>
        void SetText(DataDictionaryItemModel item)
        {
            TextBox tb = (TextBox)this.GetTemplateChild("TextBox1");
            pop.IsOpen = false;
            if (tb == null || item == null)
                return;
            switch (DictViewType)
            {
                case DictViewType.ID:
                    tb.Text = item.Id + "";
                    break;
                case DictViewType.Code:
                    tb.Text = item.DictCode;
                    break;
                case DictViewType.Name:
                    tb.Text = item.DictValue;
                    break;
                case DictViewType.CodeAndName:
                    tb.Text = item.DictCode + ":" + item.DictValue;
                    break;
                //case DictViewType.id:
                //    tb.Text = item.Id + ":" + item.DictCode;
                //    break;
                case DictViewType.IDAndName:
                    tb.Text = item.Id + ":" + item.DictValue;
                    break;
            }
            object context = this.DataContext;
            if (context == null || string.IsNullOrEmpty(Field))
                return;
            PropertyInfo pi = context.GetType().GetProperty(Field); ;
            switch (DictResultType)
            {

                case DictResultType.ID:
                    pi.SetValue(context, item.Id, null);
                    break;
                case DictResultType.Code:
                    pi.SetValue(context, item.DictCode, null);
                    break;
                case DictResultType.Name:
                    pi.SetValue(context, item.DictValue, null);
                    break;
            }
        }

        //void SetText(string Field)
        //{
        //    TextBox tb = (TextBox)this.GetTemplateChild("TextBox1");
        //    switch (DictViewType)
        //    {
        //        case DictEnum.ID:
        //            tb.Text = item.Id + "";
        //            break;
        //        case DictEnum.Code:
        //            tb.Text = item.DictCode;
        //            break;
        //        case DictEnum.Value:
        //            tb.Text = item.DictValue;
        //            break;
        //        case DictEnum.CodeAndValue:
        //            tb.Text = item.DictCode + ":" + item.DictValue;
        //            break;
        //        case DictEnum.IDAndCode:
        //            tb.Text = item.Id + ":" + item.DictCode;
        //            break;
        //        case DictEnum.IDAndValue:
        //            tb.Text = item.Id + ":" + item.DictValue;
        //            break;
        //    }
        //}

        void dg_SelectionChanged(object sender, DataGridSelectionChangedEventArgs e)
        {
            C1DataGrid dg = sender as C1DataGrid;
            if (dg.SelectedItem != null)
            {
                SetText(dg.SelectedItem as DataDictionaryItemModel);
            }
            //System.Windows.Controls.Primitives.Popup pop = (System.Windows.Controls.Primitives.Popup)this.GetTemplateChild("Popup1");
            //pop.IsOpen = false;
            btton_Click(btton, null);
        }

        void btton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.Primitives.Popup pop = (System.Windows.Controls.Primitives.Popup)this.GetTemplateChild("Popup1");
            pop.IsOpen = !pop.IsOpen;

            //pop.GotFocus += new RoutedEventHandler(pop_GotFocus);
            //pop.LostFocus -= new RoutedEventHandler(pop_LostFocus);
            //pop.LostFocus += new RoutedEventHandler(pop_LostFocus);
            Button btn1 = (Button)sender;

            GeneralTransform gtf = btn1.TransformToVisual(btn1);
            Point pPostion = gtf.Transform(new Point(0, 0));
            pop.HorizontalOffset = pPostion.X;
            pop.VerticalOffset = pPostion.Y + btn1.Height * 1.5;
            //double  Width = 0;
            //TextBox tb = (TextBox)this.GetTemplateChild("TextBox1");
            //Width = tb.ActualWidth +20;
            //Grid grid = (Grid)this.GetTemplateChild("gridinpop");
            //grid.Width = Width;
            //grid = (Grid)this.GetTemplateChild("grid2inpop");
            //grid.Width = Width;
            //grid = (Grid)this.GetTemplateChild("grid3inpop");
            //grid.Width = Width;
            //grid = (Grid)this.GetTemplateChild("grid4inpop");
            //grid.Width = Width;
            //grid = (Grid)this.GetTemplateChild("Grid1");
            //grid.Width = Width;
            //((Canvas)this.GetTemplateChild("canvas1")).Width = Width;
        }

    }
    public enum DictViewType
    {
        ID,
        Code,
        Name,
        IDAndName,
        CodeAndName
    }

    public enum DictResultType
    {
        ID,
        Code,
        Name,

    }
}
